package com.share.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.domain.Catelog;
import com.share.domain.LexCatelog;
import com.share.domain.Lexicon;
import com.share.domain.SysUser;
import com.share.dto.SysUserDto;
import com.share.mapper.LexCatelogMapper;
import com.share.service.CatelogService;
import com.share.service.LexCatelogService;
import com.share.service.LexiconService;
import com.share.mapper.LexiconMapper;
import com.share.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class LexiconServiceImpl extends ServiceImpl<LexiconMapper, Lexicon>
    implements LexiconService{


    @Autowired
    SysUserService sysUserService;

    @Autowired
    LexCatelogService lexCatelogService;

    @Autowired
    CatelogService catelogService;

    //根据id查询词条
    public Lexicon getInfoById(Long id) {
        Lexicon lexicon = this.getById(id);

        Long uid = lexicon.getUid();  //创建人
        if (uid!=null){
            SysUser sysUser = sysUserService.getById(uid);
            SysUserDto sysUserDto = new SysUserDto();
            BeanUtils.copyProperties(sysUser,sysUserDto);
            lexicon.setUser(sysUserDto);
        }
        List<LexCatelog> lexCatelogs = lexCatelogService.list(new QueryWrapper<LexCatelog>().eq("lex_id", id));
        //获取所拥有分类id集合
        List<Integer> cids = lexCatelogs.stream().map(l -> l.getCid()).collect(Collectors.toList());
        List<Catelog> catelogs = catelogService.listByIds(cids);
        lexicon.setCatelogs(catelogs);
        return lexicon;
    }



    //查询词条列表
    public Page<Lexicon> findPage(String name, Page page) {
        Page<Lexicon> lexiconPage = this.page(page, new QueryWrapper<Lexicon>().like(StrUtil.isNotBlank(name), "name", name));
        List<Lexicon> records = lexiconPage.getRecords().stream().map(lex -> {
            Long uid = lex.getUid();
            if (uid!=null){
                SysUser sysUser = sysUserService.getById(uid);
                SysUserDto userDto = new SysUserDto();
                BeanUtils.copyProperties(sysUser, userDto);
                lex.setUser(userDto);
            }

            return lex;
        }).collect(Collectors.toList());
        lexiconPage.setRecords(records);

        return lexiconPage;
    }
}




